package com.example.meet.ui;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.framework.base.BaseActivity;
import com.example.framework.bmob.User;
import com.example.framework.bmob.bmobManager.BmobManager;
import com.example.framework.entity.Constants;
import com.example.framework.manager.DialogManager;
import com.example.framework.utils.LogUtils;
import com.example.framework.utils.SpUtils;
import com.example.framework.view.DialogView;
import com.example.framework.view.LoadingView;
import com.example.framework.view.TouchPictureView;
import com.example.meet.MainActivity;
import com.example.meet.R;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.LogInListener;
import cn.bmob.v3.listener.QueryListener;

/**
 * 登录页
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener{

    /**
     * 1. 点击发送按钮，弹出提示框，是图片验证码
     * 2. 图片通过，发送验证码，同时按钮变成不可点击，按钮开始倒计时，倒计时结束，按钮可点击，文字变成发送
     * 3. 通过手机号码和验证码进行登录
     * 4. 登录成功之后获取本地对象
     */

    private EditText et_phone;
    private EditText et_code;
    private Button btn_send_code;
    private Button btn_login;
    private Button btn_agree;
    private boolean agree = false;

    private DialogView mCodeView;
    private TouchPictureView mPictureV;

    private LoadingView mLoadingView;

    // 60s倒计时
    private static int TIME = 60;
    private static final int H_TIME = 1001;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case H_TIME:
                    TIME--;
                    btn_send_code.setText(TIME + "s");
                    if (TIME > 0) {
                        mHandler.sendEmptyMessageDelayed(H_TIME, 1000);
                    } else {
                        btn_send_code.setEnabled(true);
                        btn_send_code.setText(getString(R.string.btn_login_send));
                    }
                    break;
            }
            return false;
        }
    });


    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initView();
    }

    private void initView() {
        initDialogView();

        et_phone = findViewById(R.id.et_phone);
        et_code = findViewById(R.id.et_code);
        btn_send_code = findViewById(R.id.btn_send_code);
        btn_login = findViewById(R.id.btn_login);
        btn_agree = findViewById(R.id.chose_agree_or_no);

        btn_send_code.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        btn_agree.setOnClickListener(this);

        String phone = SpUtils.getInstance().getString(Constants.SP_PHONE, "");
        if (!TextUtils.isEmpty(phone)) {
            et_phone.setText(phone);
        }

        mLoadingView = new LoadingView(this);
    }

    private void initDialogView() {
        mCodeView = DialogManager.getDialogInstance().initView(this, R.layout.dialog_code_view);
        mPictureV = mCodeView.findViewById(R.id.mPictureV);
        mPictureV.setViewResultListener(new TouchPictureView.OnViewResultListener() {
            @Override
            public void onResult() {
                mCodeView.hide();
                // 验证成功，发送短信
                sendSMS();
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_send_code:
                DialogManager.getDialogInstance().showDialog(mCodeView);
                break;
            case R.id.btn_login:
                login();
                break;
            case R.id.chose_agree_or_no:
                agree = !agree;
                LogUtils.i("是否同意了用户协议：" + agree);
                if (agree) {
                    btn_agree.setBackground(getDrawable(R.drawable.agree_foreground));
                } else {
                    btn_agree.setBackground(getDrawable(R.drawable.no_agree_foreground));
                }
                break;
        }
    }

    /**
     * 登录
     */
    private void login() {
        // 1. 获取手机号
        String phone = et_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this,
                    getString(R.string.text_login_phone_null), Toast.LENGTH_SHORT).show();
            return ;
        }
        // 2. 获取验证码
        String code = et_code.getText().toString().trim();
        if (TextUtils.isEmpty(code)) {
            Toast.makeText(this,
                    getString(R.string.text_login_code_null), Toast.LENGTH_SHORT).show();
            return;
        }
        // 3. 进行登录
        if (agree) {
            // 显示Loading
            mLoadingView.show("正在登录...");
            BmobManager.getInstance().signOrLoginByMobilePhone(phone, code, new LogInListener<User>() {
                @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                @Override
                public void done(User user, BmobException e) {
                    if (e == null) {
                        mLoadingView.hide();
                        // 登录成功
                        startActivity(new Intent(LoginActivity.this, MainActivity.class));
                        // 把手机号码保存下来，为了保证下次不用再输入
                        SpUtils.getInstance().putString(Constants.SP_PHONE, phone);
                        finish();
                    } else {
                        Toast.makeText(LoginActivity.this, "ERROR :" + e.toString(), Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } else {
            Toast.makeText(this, getString(R.string.text_agree_agreement), Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 发送短信验证码
     */
    private void sendSMS() {
        // 1. 获取手机号码
        String phone = et_phone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, getString(R.string.text_login_phone_null), Toast.LENGTH_SHORT).show();
            return ;
        }
        // 2. 请求短信验证码
        BmobManager.getInstance().requestSMS(phone, new QueryListener<Integer>() {
            @Override
            public void done(Integer integer, BmobException e) {
                if (e == null) {
                    btn_send_code.setEnabled(false);
                    mHandler.sendEmptyMessage(H_TIME);
                    Toast.makeText(LoginActivity.this,
                            getString(R.string.text_login_code_send_success), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(LoginActivity.this,
                            getString(R.string.text_login_code_send_error), Toast.LENGTH_SHORT).show();
                }
            }
        });

    }


}